<?php
include_once APPPATH . 'libraries/aliyun-php-sdk-core/Config.php';
include_once APPPATH . 'libraries/aliyun-oss-php-sdk-2.2.4/autoload.php';
use vod\Request\V20170321 as vod;
use OSS\OssClient;
use OSS\Core\OssException;
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 朋友圈 - 买家秀
 * @author heyu
 */
class Friends extends MY_Controller {
    /**
     * @var ConsumerFriendsCircleModel
     */
    public $mConFriends;
    /**
     * @var MerchantFriendsCircleModel
     */
    public $mMerFriends;

	public function __construct(){
		parent::__construct();
        $this->loadModel('ConsumerFriendsCircleModel', 'mConFriends', 'consumer');
        $this->loadModel('MerchantFriendsCircleModel', 'mMerFriends', 'merchant');
	}
	
	/**
	 * 首页
	 */
	public function index(){
        $data = array(
            'title' => '发现管理'
        );
		$this->view('friends/index', $data, 'datepicker,select2,datatable,validation');
	}
	
	/**
	 * 买家秀列表
	 */
	public function getList(){
		$data = $this->mConFriends->adminPcGetList();
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['consumer'];
            $data['aaData'][$k][] = '<textarea readonly class="form-control remaks-item sss textarea_height">'.base64_decode($v['content']).'</textarea>';
            $data['aaData'][$k][] = $v['latitude'].$v['longitude'];
            $data['aaData'][$k][] = $v['address'];
            $data['aaData'][$k][] = $v['browse_number'];
            $status = $v['status'] == 1 ? 2 : 1;
            $data['aaData'][$k][] = adminCreateBtn(array(
                'label' => $this->mConFriends->getStatus($v['status'], true),
                'icon' => '',
                'attr' => array(
                    'href' => getUrl('friends/changeStatus?id='.$v['id']),
                    'class' => 'ajax-request-btn deco',
                    'alert-message' => '是否确认'.$this->mConFriends->getStatus($status),

                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'friends',
                    'key' => 'friends-status'
                )
            ));
            $data['aaData'][$k][] = dateFormat($v['addtime']);
            $btnConfig = adminCreateBtn(array(
                'label' => '详情',
                'icon' => '',
                'attr' => array(
                    'href' => getUrl('friends/details?id='.$v['id']),
                    'class' => 'btn default btn-xs green-stripe',
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'friends',
                    'key' => 'friends-details'
                )
            ));
            $btnConfig .= ' '.adminCreateBtn(array(
                'label' => ' 删除',
                'icon' => '',
                'attr' => array(
                    'href' => getUrl('friends/delete?id='.$v['id']),
                    'class' => 'ajax-request-btn btn default btn-xs red-stripe',
                    'alert-message' => "确认要删除吗？"
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'friends',
                    'key' => 'friends-delete'
                )
            ));
            $data['aaData'][$k][] = $btnConfig;
        }
        unset($data['data']);
        echo json_encode($data);
	}

    /**
     * 详情
     */
	public function details(){
	    $id = get('id');
	    if (!$id){
	        show_404();
        }
	    $info = $this->mConFriends->getInfo($id);
        if($info['video']){
            $result = $this->showVideo($info['video']);
            if(!$result['status']){
                $this->appReturn(0, $result['message']);
            }
            $info['video'] =  $result['data']['video'];
        }
        $data = array(
            'info' => $info,
            'type' => 'consumer',
            'title' => '详情'
        );
	    $this->view('friends/details', $data, 'datatable,datepicker');
    }

    /**
     * 删除
     */
    public function delete()
    {
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mConFriends->getInfo($id, 0, 0, true);
        if (!$info){
            $this->appReturn(0, '数据不存在或已删除');
        }
        $tId=$this->mConFriends->save(array('is_delete' => 2), $id);
        if(! $tId){
            $this->ajaxReturn(0,'删除失败');
        }
        $this->ajaxReturn(1,'删除成功');
    }

    /**
     * 修改状态
     */
    public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mConFriends->getInfo($id, 1, 0, true);
        $status = $info['status'] == 1 ? 2 : 1;
        if($this->mConFriends->save(array('status' => $status), $id)){
            $this->ajaxReturn(1, '保存成功');
        }
        $this->ajaxReturn(0, '保存失败');
    }

    /************************卖家秀************************/

    /**
     * 卖家秀列表
     */
    public function getMerchantList(){
        $data = $this->mMerFriends->adminPcGetList();
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['merchant'];
            $data['aaData'][$k][] = '<textarea readonly class="form-control remaks-item sss textarea_height">'.base64_decode($v['content']).'</textarea>';
            $data['aaData'][$k][] = $v['latitude'].$v['longitude'];
            $data['aaData'][$k][] = $v['address'];
            $data['aaData'][$k][] = $v['browse_number'];
            $status = $v['status'] == 1 ? 2 : 1;
            $data['aaData'][$k][] = adminCreateBtn(array(
                'label' => $this->mMerFriends->getStatus($v['status'], true),
                'icon' => '',
                'attr' => array(
                    'href' => getUrl('friends/merchantChangeStatus?id='.$v['id']),
                    'class' => 'ajax-request-btn deco',
                    'alert-message' => '是否确认'.$this->mMerFriends->getStatus($status),

                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'feedback',
                    'key' => 'reply'
                )
            ));
            $data['aaData'][$k][] = dateFormat($v['addtime']);
            $btnConfig = adminCreateBtn(array(
                'label' => '详情',
                'icon' => '',
                'attr' => array(
                    'href' => getUrl('friends/merchantDetails?id='.$v['id']),
                    'class' => 'btn default btn-xs green-stripe',
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'feedback',
                    'key' => 'reply'
                )
            ));
            $btnConfig .= ' '.adminCreateBtn(array(
                    'label' => ' 删除',
                    'icon' => '',
                    'attr' => array(
                        'href' => getUrl('friends/merchantDelete?id='.$v['id']),
                        'class' => 'ajax-request-btn btn default btn-xs red-stripe',
                        'alert-message' => "确认要删除吗？"
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'feedback',
                        'key' => 'delete'
                    )
                ));
            $data['aaData'][$k][] = $btnConfig;
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 详情
     */
    public function merchantDetails(){
        $id = get('id');
        if (!$id){
            show_404();
        }
        $info = $this->mConFriends->getInfo($id, 2);
        $data = array(
            'info' => $info,
            'type' => 'merchant',
            'title' => '详情'
        );
        $this->view('friends/details', $data, 'datatable,datepicker');
    }

    /**
     * 删除
     */
    public function merchantDelete()
    {
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mMerFriends->getInfo($id, true);
        if (!$info){
            $this->appReturn(0, '数据不存在或已删除');
        }
        $tId=$this->mMerFriends->save(array('is_delete' => 2), $id);
        if(! $tId){
            $this->ajaxReturn(0,'删除失败');
        }
        $this->ajaxReturn(1,'删除成功');
    }

    /**
     * 修改状态
     */
    public function merchantChangeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mConFriends->getInfo($id, 2, 0, true);
        $status = $info['status'] == 1 ? 2 : 1;
        if($this->mMerFriends->save(array('status' => $status), $id)){
            $this->ajaxReturn(1, '保存成功');
        }
        $this->ajaxReturn(0, '保存失败');
    }

    /************************评论列表/点赞列表************************/

    /**
     * 评论列表
     */
    public function getCommentList(){
        $data = $this->mConFriends->adminPcGetCommentsList();
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['consumer'];
            $data['aaData'][$k][] = '<textarea readonly class="form-control remaks-item sss textarea_height">'.base64_decode($v['content']).'</textarea>';
//            $data['aaData'][$k][] = '';
            $data['aaData'][$k][] = dateFormat($v['addtime']);
            $data['aaData'][$k][] = '';
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 点赞记录
     */
    public function getPraiseList(){
        $data = $this->mConFriends->adminPcGetPraiseList();
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['consumer'];
            $data['aaData'][$k][] = dateFormat($v['addtime']);
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 视频播放
     */
    public function showVideo($videoId){
        $accessKeyId = 'LTAI9YmG9Xp8NgiQ';                    // 您的AccessKeyId
        $accessKeySecret = 'CZsLD8ahO4fa7axKTxjlsICO5mpkwA';            // 您的AccessKeySecret
        if(!$videoId){
            return array('status' => 0,'message' =>'视频地址为空', 'data' => '');
        }
        try {
            // 初始化VOD客户端并获取上传地址和凭证
            $vodClient = $this->init_vod_client($accessKeyId, $accessKeySecret);
            $playInfo = $this->get_play_info($vodClient, $videoId);
            $playList = $playInfo->PlayInfoList->PlayInfo;
            $url = $playList[1]->PlayURL;

            return array('status' => 1,'message' =>'', 'data' => array('video' => $url, 'CoverURL'=>$playInfo->VideoBase->CoverURL));

        } catch (Exception $e) {

            return array('status' => 0,'message' =>'Failed, ErrorMessage:'.$e->getMessage(), 'data' => '');
        }
    }

    private function init_vod_client($accessKeyId, $accessKeySecret) {
        $regionId = 'cn-shanghai';     // 点播服务所在的Region，国内请填cn-shanghai，不要填写别的区域
        $profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
        return new DefaultAcsClient($profile);
    }

    /**
     * 获取播放地址
     */
    private function get_play_info($client, $videoId) {
        $request = new vod\GetPlayInfoRequest();
        $request->setVideoId($videoId);
        $request->setAuthTimeout(3600*24);    // 播放地址过期时间（只有开启了URL鉴权才生效），默认为3600秒，支持设置最小值为3600秒
        $request->setAcceptFormat('JSON');
        return $client->getAcsResponse($request);
    }
}
